<!--
 * @Author: 1453937336@qq.com 1453937336@qq.com
 * @Date: 2024-04-18 18:37:23
 * @LastEditors: 1453937336@qq.com 1453937336@qq.com
 * @LastEditTime: 2024-07-16 12:33:26
 * @FilePath: \itforce-hris\src\pages\organization\components\unit-modal.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <a-modal v-model:open="open" :title="$t('单元')" :maskClosable="false">
      <a-form layout="vertical" :model="formState" ref="formRef" style="margin-top: 24px;">
        <a-row :gutter="[16, 0]">
          <a-col :span="24">
            <a-form-item :label="$t('上级单元')">
              <a-input v-if="ifInput" v-model:value="formState.parentName" allowClear @change="inputBlur"></a-input>
              <!-- <a-select
                v-else
                ref="select"
                v-model:value="formState.parentId"
                @change="selectChange"
              >
                <a-select-option v-for="(item, index) in treeList" :key="index" :value="item.id">
                  <span>{{ getLeve(item.level) }}{{ isCn ? item.nameZh : isArabic ? item.nameAr : item.nameEn }}</span>
                </a-select-option>
              </a-select> -->
              <a-cascader v-else v-model:value="formState.parentIdList" :options="treeData" change-on-select
                @blur="selectChange(formState.parentIdList)" :fieldNames="{
                  children: 'children',
                  value: 'id',
                  label: isCn ? 'nameZh' : isArabic ? 'nameAr' : 'nameEn'
                }" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('英文名称')" name="nameEn" :rules="[{ required: true, message: $t('请输入') }]">
              <a-input v-model:value="formState.nameEn" maxlength="80" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('英文缩写')" name="shortNameEn" :rules="[{ required: true, message: $t('请输入') }]">
              <a-input v-model:value="formState.shortNameEn" maxlength="20" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('中文名称')">
              <a-input v-model:value="formState.nameZh" maxlength="80" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('中文缩写')">
              <a-input v-model:value="formState.shortNameZh" maxlength="20" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('阿拉伯名称')">
              <a-input v-model:value="formState.nameAr" maxlength="80" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :label="$t('阿拉伯缩写')">
              <a-input v-model:value="formState.shortNameAr" maxlength="20" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item :label="$t('领导')">
              <a-select :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                v-model:value="formState.leaderName" mode="multiple" show-search style="width: 100%"
                :token-separators="[',']" :placeholder="$t('请选择')" :filter-option="filterOption"
                :options="lineManagerList" :fieldNames="{
                  label: 'fullName',
                  value: 'id'
                }" @change="lineManagerChange($event, 'leader')"></a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item :label="$t('单元描述')" name="description">
              <a-textarea v-model:value="formState.description" allow-clear maxlength="400" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item :label="$t('单元类型')" name="unitTypeId" :rules="[{ required: true, message: $t('请选择') }]">
              <a-select :getPopupContainer="(triggerNode) => triggerNode.parentNode" ref="select"
                v-model:value="formState.unitTypeId" :placeholder="$t('请选择')" disabled>
                <a-select-option v-for="(item, index) in unitList" :value="item.id">
                  {{ isCn ? item.nameZh : isArabic ? item.nameAr : item.nameEn }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <template #footer>
        <a-button :loading="loading" @click="handleColse">{{ $t('关闭') }}</a-button>
        <a-button class="btn-delect" type="" :loading="loading" @click="handleDelete">{{ $t('删除') }}</a-button>
        <a-button type="primary" :loading="loading" @click="handleOk">{{ $t('保存') }}</a-button>
      </template>
    </a-modal>
  </div>
</template>
<script setup>
import { ref, reactive, defineProps, nextTick, createVNode, getCurrentInstance } from 'vue'
import { Modal, message } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import {
  GetBusinessUnitTree,
  GetEnterpriseUnitType,
  PutBusinessUnitUpdate,
  GetParentBuName,
  DeleteBusinessUnitUuid,
  GetEmployee,
  GetEnterpriseInfo,
  GetOrganizationEnterprise
} from "@/api/organization/index";
import { useI18n } from 'vue-i18n';
const { t: $t } = useI18n();
import { useLanguage } from "@/hooks/index";
const { isEn, isCn, isArabic } = useLanguage();
import { findAllParents } from '@/utils/common/common'
const emits = defineEmits(['updateUnitModal', 'DeleteUnitModal'])
const props = defineProps({
  lineManagerList: { type: Array, default: [] }
});
const lineManagerList = ref([])
watch(() => props.lineManagerList, async (newVal) => {
  lineManagerList.value = newVal
},
  {
    flush: 'post',
    deep: true,
    immediate: true
  }
);
const formState = ref({
  id: '',
  parentId: null,
  parentName: '',
  nameEn: '',
  shortNameEn: '',
  nameZh: '',
  shortNameZh: '',
  nameAr: '',
  shortNameAr: '',
  description: '',
  leader: '',
  leaderName: '',
  unitTypeId: '',
  parentIdList: '',
});
const ifInput = ref(true)
const open = ref(false);
const loading = ref(false);
// const selectTreeObj = ref(null)
const treeData = ref([])
const treeLevels = ref([])
const treeList = ref([])
const getTree = (id) => {
  GetBusinessUnitTree({
    enterpriseId: id,
    includeEnterprise: true
  }).then(res => {
    treeData.value = convertValuesToString(res.data)
    treeLevels.value = addLevels(treeData.value)
    treeList.value = flattenTree(treeData.value)
  })
}
const convertValuesToString = (tree) => {
  return tree.map((node) => {
    const convertedNode = { ...node };
    if (convertedNode.children) {
      convertedNode.children = convertValuesToString(convertedNode.children);
    }
    convertedNode.nameZh = isCn && convertedNode.nameZh ? convertedNode.nameZh : convertedNode.nameEn
    convertedNode.nameAr = isArabic && convertedNode.nameAr ? convertedNode.nameAr : convertedNode.nameEn
    return convertedNode;
  });
};
const showModal = (obj) => {
  console.log('1111', obj);
  open.value = true
  formState.value = cloneDeep(obj)
  console.log('formState.value.id', formState.value.id)
  formState.value.parentIdList = findAllParents(treeData.value, formState.value.id)
  console.log('parentIdList', formState.value.parentIdList)
  formState.value.leaderName = formState.value?.leader ? JSON.parse(formState.value?.leader) : undefined
  getTree(formState.value.enterpriseId)
  getParentName(false, formState.value.uuid, formState.value.enterpriseId)
  getUnitList()
}
// 根据uuid查询父级bu名称
const getParentName = (includeSelf, uuid, enterpriseId) => {
  GetParentBuName(uuid, {
    includeSelf: includeSelf
  }).then(res => {
    nextTick(() => {
      if (res.data !== null) {
        formState.value.parentName = isCn.value && res.data.nameZh ? res.data.nameZh : isArabic.value && res.data.nameAr ? res.data.nameAr : res.data.nameEn;
        // selectTreeObj.value = res.data
      } else {
        getEnterpriseId(enterpriseId)
      }
      ifInput.value = true
    })

  })
}

const getEnterpriseId = (enterpriseId) => {
  GetOrganizationEnterprise(enterpriseId).then(res => {
    formState.value.parentName = res.data.name;
  })
}
const lineManagerChange = (v, name) => {
  formState.value[name] = JSON.stringify(v)
}

const filterOption = (input, option) => {
  return option.fullName.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

const getLeve = (num) => {
  let dotted = ''
  let dashedLine = '----';
  let numOfDashes = num > 0 ? num * 4 : 0;
  for (let i = 0; i < numOfDashes; i += 4) {
    dotted += dashedLine
  }
  return dotted
}
const inputBlur = () => {
  ifInput.value = false
}
const obj = ref({})
const selectChange = (val) => {
  console.log('val111', val);
  let parentIdValue = val[val.length - 1]
  console.log('parentIdValue', parentIdValue);
  obj.value = treeList.value.find(item => item.id === parentIdValue)
  console.log('dddd222', obj.value);
  console.log('=====', obj.value);
  if (parentIdValue === 0) { // id 是0就去查公司
    getEnterpriseInfo(obj.value.uuid)
  } else if (formState.value.id !== val) { // id不是0但选择同级选择不是自己就去查根据uuid查询父级bu名称
    getParentName(true, obj.value.uuid)
  } else {
    getParentName(false, obj.value.uuid, obj.value.enterpriseId)
  }
}

const getEnterpriseInfo = (uuid) => {
  GetEnterpriseInfo(uuid).then(res => {
    nextTick(() => {
      formState.value.parentName = res.data.name
      ifInput.value = true
    })

  })
}
const addLevels = (nodes, level = 0) => {
  return nodes.map(node => {
    node.level = level; // 添加层级标记
    if (node.children && node.children.length > 0) {
      node.children = addLevels(node.children, level + 1);
    }
    return node;
  });
}

const flattenTree = (treeData) => {
  // let flattened = [];
  // for (let node of tree) {
  //   const cloned = {...node};
  //   delete cloned.children; // 删除children属性，以便可以直接添加到结果数组中
  //   flattened.push(cloned);
  //   if (node.children && node.children.length > 0) {
  //     // 递归处理子节点
  //     flattened = flattened.concat(flattenTree(node.children, node));
  //   }
  // }
  // return flattened;
  let flatArray = [];
  function flatten(node) {
    flatArray.push(node);
    if (node.children && node.children.length > 0) {
      node.children.forEach(child => {
        flatten(child);
      });
    }
  }
  treeData.forEach(node => {
    flatten(node);
  });

  return flatArray;
}
const unitList = ref([])
const getUnitList = () => {
  GetEnterpriseUnitType({
    enterpriseId: formState.value.enterpriseId
  }).then(res => {
    unitList.value = res.data
  })
}
const handleColse = () => {
  formRef.value.resetFields();
  open.value = false
}

const formRef = ref(null);
const handleOk = () => {
  loading.value = true
  formRef.value.validate().then(() => {
    PutBusinessUnitUpdate({
      ...formState.value,
      enterpriseId: formState.value.enterpriseId
    }).then(res => {
      message.success($t('操作成功'));
      handleColse()
      console.log('最后保存===', formState.value.parentId, formState.value.id)
      emits('updateUnitModal', formState.value.parentId, formState.value.id)
    }).finally(() => {
      loading.value = false
    });
  }).catch((error) => {
    loading.value = false
    ifInput.value = true
  });
}
const handleDelete = () => {
  Modal.confirm({
    title: $t('你确定要删除吗'),
    icon: createVNode(ExclamationCircleOutlined),
    okText: $t('确定'),
    cancelText: $t('取消'),
    onOk() {
      DeleteBusinessUnitUuid({
        uuid: formState.value.uuid
      }).then(res => {
        if (res.code !== 200) return message.warning($t('操作失败'));
        message.success($t('操作成功'));
        handleColse()
        emits('DeleteUnitModal')
      })
    },
    onCancel() {
      // consolelog('Cancel');
    },
  });
}
defineExpose({
  showModal
});
</script>
<style lang="scss" scoped>
:deep(.ant-input-affix-wrapper-disabled) {
  background-color: #fff;
}
</style>
